package com.milling.web.controller.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.milling.business.BusinessConstants;
import com.milling.business.domain.WmsConfigInfo;
import com.milling.business.domain.WmsErpTask;
import com.milling.business.domain.WmsSortingInstockHistory;
import com.milling.business.service.*;
import com.milling.common.annotation.Log;
import com.milling.common.core.controller.BaseController;
import com.milling.common.core.domain.AjaxResult;
import com.milling.common.core.page.TableDataInfo;
import com.milling.common.core.redis.RedisCache;
import com.milling.common.enums.BusinessType;
import com.milling.common.utils.StringUtils;
import com.milling.common.utils.http.WmsApiUtils;
import com.milling.common.utils.modbus.ModbusServiceFactory;
import com.milling.common.utils.modbus.ModbusTcpService;
import com.milling.common.utils.poi.ExcelUtil;
import com.milling.common.utils.sql.DbUtils;
import com.milling.common.utils.uuid.UUID;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 分拣入库通知Controller
 *
 * @author X
 * @date 2025-04-09
 */
@RestController
@RequestMapping("/RestAPI")
public class WmsNeedleSortingInstockController extends BaseController
{

    @Autowired
    private IWmsErpTaskService wmsErpTaskService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private DbUtils dbUtils;

    @Autowired
    private IWmsSortingInstockHistoryService wmsSortingInstockHistoryService;

    // 从参数中读取IP、端口、slaveId和连接池大小
    @Value("${modbus.sorting.host:192.168.237.178}")
    private String host; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.port:502}")
    private int port; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.poolSize:5}")
    private int poolSize; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.slaveId:1}")
    private int slaveId;

    // 获取Modbus服务实例
    private ModbusTcpService modbusTcpService;

    @PostConstruct
    public void init() {
        // 初始化 Modbus 服务
        modbusTcpService = ModbusServiceFactory.getModbusService(host, port, poolSize);
        logger.info("FetchTasks Modbus服务初始化完成 - {}:{}", host, port);

        // 初始化扫码器连接
//        initConnection();
    }
    /**
     * 查询ERP下发任务清单列表
     */
    @PreAuthorize("@ss.hasPermi('business:erptask:list')")
    @GetMapping("/list")
    public TableDataInfo list(WmsErpTask wmsErpTask)
    {
        startPage();
        List<WmsErpTask> list = wmsErpTaskService.selectWmsErpTaskList(wmsErpTask);
        return getDataTable(list);
    }

    @PostMapping("/UploadDrillOK")
    @ApiOperation(value = "配针任务接口", notes = "预配针接口")
    public AjaxResult UploadDrillOK(@RequestBody String jsonString) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        logger.info("IP is: " + getIpAddress(httpServletRequest));

        logger.info(jsonString);
        AjaxResult ajaxResult = AjaxResult.success();
        String msg = "接收成功";
        String code = "200";

        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonString);

            String macCode = jsonObject.getString("MacCode");
            String transCode = jsonObject.getString("TransCode");
            String m_Drill_Info = jsonObject.getString("m_Drill_Info");
            String drillInfo = jsonObject.getString("DrillInfo");
            String timestamp = jsonObject.getString("Timestamp");
            logger.info("macCode: " + macCode + ", transCode: " + transCode + ", m_Drill_Info: " + m_Drill_Info + ", drillInfo: " + drillInfo + ", timestamp: " + timestamp);

            WmsSortingInstockHistory instockHistory = new WmsSortingInstockHistory();
            instockHistory.setStatus(BusinessConstants.SORTING_INSTOCK_STATUS_INSTOCKING);
            instockHistory.setTransCode(transCode);
//                    instockHistory
            List<WmsSortingInstockHistory> instockHistoryList = wmsSortingInstockHistoryService.selectWmsSortingInstockHistoryList(instockHistory);
            if(null != instockHistoryList && instockHistoryList.size() > 0) {
                WmsSortingInstockHistory updateInstockHistory = instockHistoryList.get(0);
                //写入返回包 及 修改状态
                updateInstockHistory.setUpdateTime(new Date());
                updateInstockHistory.setResBody(jsonString);
                updateInstockHistory.setStatus(BusinessConstants.SORTING_INSTOCK_STATUS_INSTOCK);//待入库
                wmsSortingInstockHistoryService.updateWmsSortingInstockHistory(updateInstockHistory);
            }
            //处理流程
            ajaxResult.put("macCode", macCode);
            ajaxResult.put("transCode", transCode);

        } catch (Exception e) {
            e.printStackTrace();
            code = "202";
            msg = "数据格式异常";
        }
        ajaxResult.put("msg", msg);
        ajaxResult.put("code", code);
        logger.info(ajaxResult.toString());

        //5021地址写入1，通知PLC
        try {
            modbusTcpService.writeHoldingRegister(1, 5021, 1);
        } catch (ModbusTransportException e) {
            e.printStackTrace();
            logger.error("通知PLC入库完成失败");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("通知PLC入库完成失败");
        }

        long endTime = System.currentTimeMillis(); // 记录结束时间
        long duration = endTime - startTime; // 计算执行时间
        logger.info("postData executed in {} ms", duration); // 输出执行时间

        return ajaxResult;
    }

    @PostMapping("/ManualOutBoundDetail")
    @ApiOperation(value = "通知下料针盒明细", notes = "下料每一个针盒到达指定位置时下发")
    public AjaxResult ManualOutBoundDetail(@RequestBody String jsonString) {
        long startTime = System.currentTimeMillis(); // 记录开始时间
        logger.info("IP is: " + getIpAddress(httpServletRequest));

        logger.info(jsonString);
        AjaxResult ajaxResult = AjaxResult.success();
        String msg = "接收成功";
        String code = "200";

        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonString);

            String macCode = jsonObject.getString("MacCode");
            String boxCode = jsonObject.getString("m_Drill_Box_Code");
//            String m_Drill_Info = jsonObject.getString("m_Drill_Info");
//            String drillInfo = jsonObject.getString("DrillInfo");
            String m_Drill_Type = jsonObject.getString("m_Drill_Type");
            String m_Drill_Grind_Count = jsonObject.getString("m_Drill_Grind_Count");
            String timestamp = jsonObject.getString("Timestamp");
            logger.info("macCode: " + macCode + ", boxCode: " + boxCode + ", m_Drill_Type: " + m_Drill_Type + ", m_Drill_Grind_Count: " + m_Drill_Grind_Count + ", timestamp: " + timestamp);

            //处理流程
            ajaxResult.put("macCode", "D001");
            ajaxResult.put("m_Drill_Box_Code", boxCode);
            ajaxResult.put("Code", "0");
            ajaxResult.put("Message", "ok");
            ajaxResult.put("Timestamp", "0");
        } catch (Exception e) {
            e.printStackTrace();
            code = "202";
            msg = "数据格式异常";
        }
        ajaxResult.put("msg", msg);
        logger.info(ajaxResult.toString());

        long endTime = System.currentTimeMillis(); // 记录结束时间
        long duration = endTime - startTime; // 计算执行时间
        logger.info("postData executed in {} ms", duration); // 输出执行时间

        return ajaxResult;
    }

    /**
     * 获取ERP下发任务清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:erptask:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wmsErpTaskService.selectWmsErpTaskById(id));
    }

    /**
     * 新增ERP下发任务清单
     */
    @PreAuthorize("@ss.hasPermi('business:erptask:add')")
    @Log(title = "ERP下发任务清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WmsErpTask wmsErpTask)
    {
        return toAjax(wmsErpTaskService.insertWmsErpTask(wmsErpTask));
    }

    /**
     * 修改ERP下发任务清单
     */
    @PreAuthorize("@ss.hasPermi('business:erptask:edit')")
    @Log(title = "ERP下发任务清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmsErpTask wmsErpTask)
    {
        return toAjax(wmsErpTaskService.updateWmsErpTask(wmsErpTask));
    }

    /**
     * 删除ERP下发任务清单
     */
    @PreAuthorize("@ss.hasPermi('business:erptask:remove')")
    @Log(title = "ERP下发任务清单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wmsErpTaskService.deleteWmsErpTaskByIds(ids));
    }
}
